package com.atom.common.delegate;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.atom.common.DelegateType;

@Service
public class DelegateTask {
  
  private static Logger logger = Logger.getLogger(DelegateTask.class);

  private ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

  @Resource DelegateInfoDao delegateInfoDao;
  @Resource HistoricDelegateDao historicDelegateDao;

  @Resource AddOutDelegateHandler addOutDelegateHandler;
  @Resource AddCoopDelegateHandler addCoopDelegateHandler;
  @Resource DelOutDelegateHandler delOutDelegateHandler;
  @Resource DelCoopDelegateHandler delCoopDelegateHandler;

  //@Scheduled(cron = "0/5 * * * * ? ")
  public void myAddTask() {
    logger.info("========ADD START=========");
    Date current = new Date();
    List<DelegateInfo> list = delegateInfoDao.getAddDelegateList(current);

    for (final DelegateInfo info : list) {
      cachedThreadPool.execute(new Runnable() {         
        public void run() {  
          if (info.getDelegateType() ==  DelegateType.COOP) {
            addCoopDelegateHandler.add(info);
          }
          if (info.getDelegateType() ==  DelegateType.OUT) {
            addOutDelegateHandler.add(info);
          }
        }  
      });  
    }
  }
  
  //@Scheduled(cron = "0/5 * * * * ? ")
  public void myDelTask() {
    logger.info("========DEL START=========");
    Date current = new Date();
    List<DelegateInfo> list = delegateInfoDao.getDelDelegateList(current);

    for (final DelegateInfo info : list) {
      cachedThreadPool.execute(new Runnable() {         
        public void run() {  
          if (info.getDelegateType() ==  DelegateType.OUT) {
            delOutDelegateHandler.del(info);
          }
          if (info.getDelegateType() ==  DelegateType.COOP) {
            delCoopDelegateHandler.del(info);
          }
        }  
      });  
    }
  }

}
